package com.eco.fanliapp.job.orderjobNew;


import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 绑定订单批量处理
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class OrderBindingUserTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(OrderBindingUserTask.class);

    @Autowired
    private ISyUserUnboundedOrderApplyService syUserUnboundedOrderApplyService;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private ITaoBaoOrderNewService taoBaoOrderNewService;
    @Autowired
    private IAppOrderDetailService appOrderDetailService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private ITaobaoSchemeService taobaoSchemeService;

    public OrderBindingUserTask() {}

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行绑定订单批量处理定时扫描任务-OrderBindingUserTask：executeCount=" + executeCount + "--startTime=" + startTime);


        try {
            //查询绑定的订单(已提交，已启用，未删除)
            List<SyUserUnboundedOrderApply> list1 = syUserUnboundedOrderApplyService.selectOrderDetailBatch();

            for(SyUserUnboundedOrderApply unboundedOrder:list1){
                //操作绑定订单的状态
                boolean flag = true;
                //分佣状态
                boolean flagBag = false;
                AppOrderDetail appOrderDetail = null;
                TaobaoScheme taobaoScheme = null;
                AppGoods appGoods = null;

                //绑定人详情（渠道，会员不能为空）
                AppUser appUser = appUserService.selectAppUserByUserId(unboundedOrder.getUserId());
                if(appUser == null || appUser.getSchemeId()==0 || (appUser.getSpecialId() == 0 && appUser.getRelationId() == 0) ){
                    flag = false;
                }

                //查询联盟数据
                if(flag){
                    taobaoScheme = taobaoSchemeService.selectTaobaoSchemeById(appUser.getSchemeId());
                    if(taobaoScheme == null){
                        flag = false;
                    }
                }

                //订单详情（渠道，会员不能为空）
                if(flag){
                    appOrderDetail = appOrderDetailService.selectAppOrderDetailByTradeId(unboundedOrder.getOrderId());
                    if(appOrderDetail == null || appOrderDetail.getRelationId() != 0 || appOrderDetail.getSpecialId() !=0){
                        flag = false;
                    }
                }

                //订单的site_id、adzone_id要和用户（会员运营id）授权的联盟对应的site_id、adzone_id对应一致（联盟对应推广位）
                if(flag){
                    String generalizePid = taobaoScheme.getGeneralizePid();
                    String siteId = appOrderDetail.getSiteId();
                    String adzoneId = appOrderDetail.getAdzoneId();
                    if(!generalizePid.contains(siteId)|| !generalizePid.contains(adzoneId)){
                        flag = false;
                    }
                }

                //商品详情
                if(flag){
                    appGoods = taoBaoOrderNewService.getAppgoods(appOrderDetail.getItemId().toString(), appOrderDetail);
                    if(appGoods == null){
                        flag = false;
                    }
                }

                //校验是否重复处理
                if(flag){
                    List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(appOrderDetail.getTradeId());
                    if(CollectionUtils.isNotEmpty(userOrders)){
                        flag = false;
                    }
                }

                //====《开始分佣》===
                if(flag){
                    flagBag = taoBaoOrderNewService.handleBindingOrder(appUser, appOrderDetail, appGoods);
                    if(flagBag){
                        //更新订单绑定时间
                        appOrderDetail.setBinding(1);
                        appOrderDetail.setBindingTime(new Date());
                        appOrderDetailService.updateById(appOrderDetail);
                    }
                }

                //更新绑定订单的状态
                unboundedOrder.setStatus(flag?1:2);
                unboundedOrder.setBingTime(new Date());
                unboundedOrder.setCommissionDealResult(flagBag?1:0);
                syUserUnboundedOrderApplyService.updateById(unboundedOrder);
            }

            //判断是否存在过期未处理
            List<SyUserUnboundedOrderApply> list = syUserUnboundedOrderApplyService.selectBatchDate();
            //批量更新
            if(CollectionUtils.isNotEmpty(list)){
                syUserUnboundedOrderApplyService.updateBatchById(list);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行免单过期商品定时扫描任务错误");
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行绑定订单批量处理定时扫描任务-OrderBindingUserTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }


}
